import { loginApi, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    user: null //存储登录后的用户的信息
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  /* SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }, */
  SET_USER: (state, played) => {
    state.user = played
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    // userInfo 是用户提交的数据, 然后将这个数据发送到服务器
    return new Promise((resolve, reject) => {
      loginApi(userInfo).then((result) => {
        const { data } = result;
        if (data) { //如果有数据
          commit('SET_USER', data)
          resolve()
        } else {
          reject(result)
        }
      }).catch((error) => reject(error))
    })
  },

  // 恢复登录
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (typeof response === 'string') { //未登录
          response = JSON.parse(response)
          //请求未成功或者是token过期
          if (response.code === 401) {
            reject(response.msg)
          }
        } else { //请求成功
          commit('SET_USER', response.data)
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登录
  logout({ commit}) {
    return new Promise((resolve, reject) => {
      removeToken() // 清除token
      resetRouter()
      commit('RESET_STATE')
      resolve()
      /*  logout(state.token).then(() => {
         
         resolve()
       }).catch(error => {
         reject(error)
       }) */
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

